package cn.dengta.webapp.trade.dto;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nonnull;

import cn.dengta.common.model.Status;
import cn.dengta.context.model.WesKit;
import cn.dengta.context.rpc.CachedConfig;
import cn.dengta.context.rpc.CachedConfigManager;
import cn.dengta.webapp.user.model.AppMenuType;
import lombok.Getter;
import lombok.Setter;

/**
 * APP入口开关配置
 */
@Getter
@Setter
public class AppSwitchWesKitConfig {

	/** 第一个是 isOpenAll，从第二个开始，参见{@link AppMenuType} */
	// protected int[] hidden;
	private Map<WesKit, int[]> hiddenMap;

	public AppSwitchWesKitConfig() {
		WesKit[] wesKits = WesKit.values();
		HashMap<WesKit, int[]> wesKitHashMap = new HashMap<>(wesKits.length);
		for (WesKit wesKit : WesKit.values()) {
			final int[] switches = new int[AppMenuType.CACHE.length + 1];
			final AppMenuType[] defHidden = { AppMenuType.CASH, AppMenuType.CN_INTEGRAL, AppMenuType.CN_CASH, AppMenuType.GAME, AppMenuType.FB, AppMenuType.SEARCH };
			for (AppMenuType hide : defHidden) {
				switches[hide.value] = 1;
			}
			wesKitHashMap.put(wesKit, switches);
		}
		hiddenMap = wesKitHashMap;

	}

	public AppSwitchWesKitConfig(Map<WesKit, int[]> hiddenMap) {
		this.hiddenMap = hiddenMap;
	}

	public static AppSwitchWesKitConfig getDefault() {
		return new AppSwitchWesKitConfig();
	}

	public void setHidden(Map<WesKit, int[]> hiddenMap) {
		if (hiddenMap != null) {
			Map<WesKit, int[]> hiddenMap1 = new AppSwitchWesKitConfig().hiddenMap;
			this.hiddenMap = hiddenMap;
		}
	}

	public boolean openAll(WesKit wesKit) {
		int[] ints = hiddenMap.get(wesKit);
		return ints[0] == 1;
	}

	public static boolean isOpenAll(WesKit wesKit) {
		if (wesKit == null) {
			return false;
		}
		return cache().get().openAll(wesKit);
	}

	public static boolean isOpen(@Nonnull AppMenuType type, WesKit wesKit) {
		if (wesKit == null) {
			return false;
		}
		return Status.asResult(cache().get().hiddenMap.get(wesKit)[type.value]);
	}

	/** 是否关闭了对应的开关 */
	public boolean isClosedSwitch(AppMenuType type, WesKit wesKit) {
		return !isOpen(type, wesKit);
	}

	/** 是否关闭了对应的开关 */
	public static boolean isClosed(AppMenuType type, WesKit wesKit) {
		return cache().get().isClosedSwitch(type, wesKit);
	}

	public Map<String, Boolean> expose(WesKit wesKit) {

		int[] hidden = this.hiddenMap.get(wesKit);
		final HashMap<String, Boolean> map = new HashMap<>(hidden.length, 1F);
		map.put("isOpenAll", hidden[0] == 1);
		for (AppMenuType type : AppMenuType.CACHE) {
			map.put(type.label, hidden[type.value] == 1);
		}
		return map;
	}

	public static CachedConfig<AppSwitchWesKitConfig> cache() {
		return InstanceHolder.instance;
	}

	private static final class InstanceHolder {

		static final CachedConfig<AppSwitchWesKitConfig> instance = CachedConfigManager.create(AppSwitchWesKitConfig.class, AppSwitchWesKitConfig::getDefault);

	}

}
